<template>
  <div class="bar-code">
    <canvas ref="canvas" style="width: 100%" />
  </div>
</template>

<script>
import JsBarcode from 'jsbarcode';

export default {
  name: 'BarCode',
  props: {
    value: {
      type: String,
      default: '',
    },
    showText: {
      type: Boolean,
      default: false,
    },
    text: {
      type: String,
      default: '',
    },
  },
  watch: {
    value: {
      handler(nv) {
        this.generateBarCode(nv);
      },
      immediate: true,
    },
    showText: {
      handler(nv) {
        this.generateBarCode(this.value);
      },
    },
    text: {
      handler(nv) {
        this.generateBarCode(this.value);
      },
    },
  },
  methods: {
    generateBarCode(text) {
      if (this.$refs.canvas) {
        const options = {
          text: this.text || text,
          displayValue: this.showText,
          fontSize: 10,
          height: 20,
          width: 2,
        };
        console.log('Generating barcode with text:', this.$refs.canvas, options.text);
        JsBarcode(this.$refs.canvas, text, options);
      }
    },
  },
  mounted() {
    this.generateBarCode(this.value);
  },
};
</script>
